package be.bejug.setris.swinggui

import javax.swing.{JComponent}
import be.bejug.setris.{Tile, TileGrid}
import java.awt.{Insets, Dimension, Graphics}

/**
 * User: Peter
 * Date: 27-mei-2010
 * Time: 7:19:28
 */


class TileGridView(private var _data:TileGrid,val tileSize:Int=12) extends JComponent{
	def	data = _data
	def	data_=(data:TileGrid) {
		_data	=	data
		repaint()
	}


	override def getPreferredSize: Dimension = {
		val	insets	=	if(getInsets == null) new Insets(0,0,0,0) else getInsets
		new Dimension(data.width*tileSize+insets.left+insets.right,data.height*tileSize+insets.top+insets.bottom)
	}

	override def getMinimumSize: Dimension = getPreferredSize

	override def paint(g: Graphics): Unit = {
		super.paint(g);
		g.setColor(getBackground)
		g.fillRect(0,0,getWidth,getHeight)
		val	insets	=	if(getInsets == null) new Insets(0,0,0,0) else getInsets
		val	prefSize	=	getPreferredSize
		val x=insets.left + (getWidth-prefSize.width)/2
		val y=insets.top + (getHeight-prefSize.height)/2
		for(ix <- (0 until data.width); iy<-(0 until data.height)){
			data(ix,iy) match {
				case Some(t) => drawTile(g,x+ix*tileSize,y+iy*tileSize,t)
				case None => drawEmptyTile(g,x+ix*tileSize,y+iy*tileSize)
			}
		}
		if(getBorder != null){

			getBorder.paintBorder(this,g,x-insets.left,y-insets.top,prefSize.width,prefSize.height)
		}
	}

	private	def	drawEmptyTile(g:Graphics,x:Int,y:Int){
		g.setColor(getForeground)
		g.drawRect(x,y,tileSize-1,tileSize-1)
	}

	private	def	drawTile(g2:Graphics,x:Int,y:Int,tile:Tile){
		val	lighter	=	tile.color.brighter.brighter.brighter
		val	darker	=	tile.color.darker

		g2.setColor(tile.color)
		g2.fillRect(x,y,tileSize,tileSize);
		for(b <- 0 until 2){
			g2.setColor(lighter)
			g2.drawLine(x+b,y+b,x+tileSize-1-b,y+b)
			g2.drawLine(x+b,y+b,x+b,y+tileSize-1-b)
			g2.setColor(darker)
			g2.drawLine(x+tileSize-1-b,y+b,x+tileSize-1-b,y+tileSize-1-b)
			g2.drawLine(x+b,y+tileSize-1-b,x+tileSize-1-b,y+tileSize-1-b)
		}
	}
}











